setwd("../../data/voter_file_aggregated")

files <- c("07to09","09to10","10to12","12to14")

## pdf("moving_changing_party_all_simple_noagecontrol.pdf",width=6,height=5)
par(mar=c(5,6,1,1))

for (file in files) {

the.col <- "black"
if (file=="07to09") {
    the.col <- "purple3"
}
if (file=="12to14") {
    the.col <- "darkorange"
}
if (file=="09to10") {
    the.col <- "gray"
}

load(paste("moves_distance_",file,"_simple_noagecontrol.RData",sep=""))
the.coefs <- the.coefs[grep("cut",names(the.coefs))]
##
distances <- cbind(
    as.numeric(sapply(strsplit(gsub(")", "",gsub(paste("cut(((move",file,".distance)), the.brks, right = FALSE)[",sep=""),"",names(the.coefs),fixed=T),fixed=T), ","), "[", 1))
    )
gm_mean = function(x, na.rm=TRUE){
  exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x))
}
the.coefs <- data.frame(
    distance=apply(distances, 1, gm_mean),
    est=unname(the.coefs)
    )

the.cis <- the.cis[grep("cut",row.names(the.cis)),]
the.cis <- data.frame(
    distance=apply(distances, 1, gm_mean),
    lower=unname(the.cis[,1]),
    upper=unname(the.cis[,2])
    )

if (file == "07to09") {
with(
    the.coefs,
    plot(
        log(distance+1), est, xaxt="n", #floor(est)*(1 - (1+the.coefs$est)^2)
        pch=16,
        xlim=c(0, max(log(the.cis$distance+1))),
        ylim=c(
            min(the.cis$lower),
            max(c(0,0.005))
            ),
        cex.lab=1.3,
        bty="n",
        xlab="",
        ylab="Party affiliation switch\n", col=the.col
        )
    )
mtext("Miles from previous residence",side=1,padj=3,cex=1.3)
mtext("(compared to voters moving less than two miles)",side=2,padj=-5)
mtext("(in same county, median in quantile)",side=1,padj=6) #, ^2
axis(1, at = 0:5, labels=round(c(0, exp(1:5)*0.62), 1))
points(0,0,pch=16)
} else {
with(
    the.coefs,
    points(
        log(distance+1), est,
        pch=16, col=the.col
        )
    )
}

 if (file != "09to10") {
with(
    the.coefs,
    lines(
        loess.smooth(c(0, log(distance+1)), c(0, est),span=ifelse(file=="12to14",0.9,1),degree=ifelse(file=="12to14",2,1), family="gaussian"),
        lwd=3, col=the.col
        )
    )
}

abline(h = 0, lty = 2, col = "red")
}
legend(0.25,-0.015,c("2006-2008","2008-2010","2010-2012","2012-2014"),col=c("purple3","gray","black","darkorange"),pch=16, bty="n",cex=1,pt.cex=1)
## dev.off()
